//
//  TDAudienceController.m
//  liveDemo
//
//  Created by tuandai on 2017/4/10.
//  Copyright © 2017年 tuandai. All rights reserved.
//

#import "TDAudienceController.h"
#import "TCLiveListModel.h"
#import <TXRTMPSDK/TXLivePlayer.h>
#import "TCMsgHandler.h"
#import <AVFoundation/AVFoundation.h>
#import "TCUserInfoMgr.h"
#import "TCPlayerMgr.h"
#import "TCIMPlatform.h"
#import "TDAudienceView.h"

@interface TDAudienceController ()<TXLivePlayListener>

// 直播用户信息
@property (nonatomic, strong) TCLiveInfo *liveInfo;
// 拉流相关设置
@property (nonatomic, strong) TXLivePlayer *txLivePlayer;
// 群组相关处理
@property (nonatomic, strong) AVIMMsgHandler *msgHandler;
// 播放的类型
@property (nonatomic, assign) TX_Enum_PlayType playType;
// 是否进入了聊天室
@property (nonatomic, assign) BOOL isNotifiedEnterGroup;
// 渲染的view
@property (weak, nonatomic) IBOutlet UIView *videoParentView;
// 是否停止播放
@property (nonatomic, assign) BOOL videoPause;
// 是否在后台
@property (nonatomic, assign) BOOL appIsInterrupt;
// 观众的IM,弹幕，礼物逻辑处理View
@property (nonatomic, strong) TDAudienceView *audienceView;
@end

NSString *const kTCLivePlayError = @"kTCLivePlayError";
static NSString *lookAddress = @"rtmp://8895.liveplay.myqcloud.com/live/8895_a2732b5179";
@implementation TDAudienceController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"我是观众";
    
    [self initPullObject];
    
    [self joinGroup];
    
    self.videoParentView.tag = 10000;
    
    [self setVideoView];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
    // 继续播放
    if (_videoPause && _txLivePlayer) {
        [_txLivePlayer resume];
        _videoPause =NO;
    }
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    if (!_videoPause && _txLivePlayer) {
        [_txLivePlayer pause];
        _videoPause = YES;
    }
}

-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"我销毁了啊");
}

- (void)initPullObject {
    // 开启硬件加速
    self.txLivePlayer.enableHWAcceleration = YES;
    self.audienceView.msgHandler = self.msgHandler;
    self.audienceView.txLivePlayer = self.txLivePlayer;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAudioSessionEvent:) name:AVAudioSessionInterruptionNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppDidEnterBackGround:) name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppWillEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
}

#pragma mark - 加入群组
-(void) joinGroup {
    if ([[TIMManager sharedInstance] getLoginUser] == nil) {
        [[TCIMPlatform sharedInstance] onForceOfflineAlert];
        return;
    }
    
    TCUserInfoData  *hostInfo = [[TCUserInfoMgr sharedInstance] getUserProfile];
    @weakify(self)
    [self.msgHandler joinLiveRoom:_liveInfo.groupid handler:^(int errCode) {
        if (0 == errCode)
        {
            [self.msgHandler sendEnterLiveRoomMessage:hostInfo.identifier nickName:hostInfo.nickName headPic:hostInfo.faceURL];
            
            [weak_self startPlay];
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"加入群组失败--%d",errCode]];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self closeVCWithRefresh:YES];
            });
            
        }
    }];
    
    //通知业务服务器有观众加群
    NSString* realGroupId = _liveInfo.groupid;
    //录播文件由于group已经解散，故使用fileid替代groupid
    if (TCLiveListItemType_Record == _liveInfo.type)
        realGroupId = _liveInfo.fileid;
    
    [[TCPlayerMgr sharedInstance] enterGroup:hostInfo.identifier type:_liveInfo.type liveUserId:_liveInfo.userid groupId:realGroupId nickName:hostInfo.nickName headPic:hostInfo.faceURL handler:^(int errCode) {
        
        //初始化群成员列表（会主动从业务服务器拉取一次群成员列表）
//        [_logicView initAudienceList];
    }];
    
    _isNotifiedEnterGroup = YES;
    
}



#pragma mark - 开始播放
- (BOOL)startPlay {
    // 1. 检查推流链接格式是否正确
    if (![self checkPlayUrl:self.liveInfo.playurl]) {
        return NO;
    }
    
    int result = [self.txLivePlayer startPlay:self.liveInfo.playurl type:_playType];
    if (result == -1)
    {
        [self closeVCWithRefresh:YES];
        return NO;
    }
    
    if( result != 0)
    {
        [self toastTip:[NSString stringWithFormat:@"%@%d", kErrorMsgRtmpPlayFailed, result]];
        [self closeVCWithRefresh:YES];
        return NO;
    }
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
    
    return YES;
}

#pragma mark - 关闭房间逻辑处理
- (void)closeVCWithRefresh:(BOOL)refresh {
    [self stopRtmp];
    [self.audienceView closeRoom];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    if (_liveInfo) {
        
        if (_isNotifiedEnterGroup)
        {
            if (_msgHandler)
            {
                TCUserInfoData  *profile = [[TCUserInfoMgr sharedInstance] getUserProfile];
                [_msgHandler sendQuitLiveRoomMessage:profile.identifier nickName:profile.nickName headPic:profile.faceURL];
                [_msgHandler releaseIMRef];
                
                [_msgHandler quitLiveRoom:_liveInfo.groupid handler:^(int errCode) {
                    
                }];
            }
            
            //通知业务服务器观众退群
            TCUserInfoData  *hostInfo = [[TCUserInfoMgr sharedInstance] getUserProfile];
            NSString* realGroupId = _liveInfo.groupid;
            //录播文件由于group已经解散，故使用fileid替代groupid
//            if (TCLiveListItemType_Record == _liveInfo.type)
//                realGroupId = _liveInfo.fileid;
            
            [[TCPlayerMgr sharedInstance] quitGroup:hostInfo.identifier type:_liveInfo.type liveUserId:_liveInfo.userid groupId:realGroupId handler:^(int errCode) {
                
            }];
        }
    }
    if (refresh) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter] postNotificationName:kTCLivePlayError object:self];
        });
    }
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)stopRtmp{
    if(_txLivePlayer != nil)
    {
        _txLivePlayer.delegate = nil;
        [_txLivePlayer stopPlay];
        [_txLivePlayer removeVideoWidget];
    }
    [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
}



#pragma mark - 设置渲染view
- (void)setVideoView {
    [self clearLog];
    
    
    [self.txLivePlayer setupVideoWidget:self.view.frame containView:_videoParentView insertIndex:0];
    // 横屏
//    if (_rotate) {
//        [self.txLivePlayer setRenderRotation:HOME_ORIENTATION_RIGHT];
//    }
}

// 清除日志
- (void)clearLog {
    
}

#pragma mark - 拉推流情况
-(void) onPlayEvent:(int)EvtID withParam:(NSDictionary*)param {
    
}

-(void) onNetStatus:(NSDictionary*) param{
    
}


#pragma mark - 检查拉流url
-(BOOL)checkPlayUrl:(NSString*)playUrl {
    if (!([playUrl hasPrefix:@"http:"] || [playUrl hasPrefix:@"https:"] || [playUrl hasPrefix:@"rtmp:"] )) {
        [self toastTip:@"播放地址不合法，目前仅支持rtmp,flv,hls,mp4播放方式!"];
        return NO;
    }
    if (1) { // 直播
        if ([playUrl hasPrefix:@"rtmp:"]) {
            _playType = PLAY_TYPE_LIVE_RTMP;
        } else if (([playUrl hasPrefix:@"https:"] || [playUrl hasPrefix:@"http:"]) && [playUrl rangeOfString:@".flv"].length > 0) {
            _playType = PLAY_TYPE_LIVE_FLV;
        } else{
            [self toastTip:@"播放地址不合法，直播目前仅支持rtmp,flv播放方式!"];
            return NO;
        }
    }
//    else { // 点播或者UGC录制
//        if ([playUrl hasPrefix:@"https:"] || [playUrl hasPrefix:@"http:"]) {
//            if ([playUrl rangeOfString:@".flv"].length > 0) {
//                _playType = PLAY_TYPE_VOD_FLV;
//            } else if ([playUrl rangeOfString:@".m3u8"].length > 0){
//                _playType= PLAY_TYPE_VOD_HLS;
//            } else if ([playUrl rangeOfString:@".mp4"].length > 0){
//                _playType= PLAY_TYPE_VOD_MP4;
//            } else {
//                [self toastTip:@"播放地址不合法，点播目前仅支持flv,hls,mp4播放方式!"];
//                return NO;
//            }
//            
//        } else {
//            [self toastTip:@"播放地址不合法，点播目前仅支持flv,hls,mp4播放方式!"];
//            return NO;
//        }
//    }
    
    return YES;
}


#pragma mark - 前台后台处理
//在低系统（如7.1.2）可能收不到这个回调，请在onAppDidEnterBackGround和onAppWillEnterForeground里面处理打断逻辑
- (void) onAudioSessionEvent: (NSNotification *) notification
{
    NSDictionary *info = notification.userInfo;
    AVAudioSessionInterruptionType type = [info[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
    if (type == AVAudioSessionInterruptionTypeBegan) {
        if (_appIsInterrupt == NO) {
            if (_playType == PLAY_TYPE_VOD_FLV || _playType == PLAY_TYPE_VOD_HLS || _playType == PLAY_TYPE_VOD_MP4) {
                if (!_videoPause) {
                    [_txLivePlayer pause];
                }
            }
            _appIsInterrupt = YES;
        }
    }else{
        AVAudioSessionInterruptionOptions options = [info[AVAudioSessionInterruptionOptionKey] unsignedIntegerValue];
        if (options == AVAudioSessionInterruptionOptionShouldResume) {
            if (_appIsInterrupt == YES) {
                if (_playType == PLAY_TYPE_VOD_FLV || _playType == PLAY_TYPE_VOD_HLS || _playType == PLAY_TYPE_VOD_MP4) {
                    if (!_videoPause) {
                        [_txLivePlayer resume];
                    }
                }
                _appIsInterrupt = NO;
            }
        }
    }
}



- (void)onAppDidEnterBackGround:(UIApplication*)app {
    if (_appIsInterrupt == NO) {
        if (_playType == PLAY_TYPE_VOD_FLV || _playType == PLAY_TYPE_VOD_HLS || _playType == PLAY_TYPE_VOD_MP4) {
            if (!_videoPause) {
                [_txLivePlayer pause];
            }
        }
        _appIsInterrupt = YES;
    }
}

- (void)onAppWillEnterForeground:(UIApplication*)app {
    if (_appIsInterrupt == YES) {
        if (_playType == PLAY_TYPE_VOD_FLV || _playType == PLAY_TYPE_VOD_HLS || _playType == PLAY_TYPE_VOD_MP4) {
            if (!_videoPause) {
                [_txLivePlayer resume];
            }
        }
        _appIsInterrupt = NO;
    }
}


- (IBAction)closeBtnClick:(UIButton *)sender {
    [self closeVCWithRefresh:NO];
}



- (void)toastTip:(NSString *)str {
    [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",str]];
}

#pragma mark - 懒加载
-(AVIMMsgHandler *)msgHandler {
    if (!_msgHandler) {
        _msgHandler = [[AVIMMsgHandler alloc] init];
    }
    return _msgHandler;
}

-(TCLiveInfo *)liveInfo {
    if (!_liveInfo) {
        _liveInfo = [TCLiveInfo new];
        _liveInfo.playurl = lookAddress;
    }
    return _liveInfo;
}


-(TXLivePlayer *)txLivePlayer {
    if (!_txLivePlayer) {
        _txLivePlayer = [TXLivePlayer new];
        _txLivePlayer.delegate = self;
        
    }
    return _txLivePlayer;
}

-(TDAudienceView *)audienceView {
    if (!_audienceView) {
        _audienceView = [TDAudienceView createView];
        [self.videoParentView insertSubview:_audienceView atIndex:0];
        _audienceView.msgHandler = self.msgHandler;
        
        [_audienceView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(self.videoParentView);
        }];
    }
    return _audienceView;
}
    
    
@end
